package com.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chat.entry.dto.group.ReadAllMessageDTO;
import com.chat.entry.dto.group.ReadSingleMessageDTO;
import com.chat.entry.enums.ReadStatus;
import com.chat.entry.po.GroupMessageUnread;
import com.chat.entry.vo.group.GroupMessageWithUnreadVO;
import com.chat.mapper.GroupMessageUnreadMapper;
import com.chat.mapper.UserMessageMapper;
import com.chat.result.Result;
import com.chat.service.IGroupMessageUnreadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 群未读表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-09-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GroupMessageUnreadServiceImpl extends ServiceImpl<GroupMessageUnreadMapper, GroupMessageUnread> implements IGroupMessageUnreadService {
    private final UserMessageMapper userMessageMapper;

    @Override
    public Result singleMessageRead(ReadSingleMessageDTO readSingleMessageDTO) {
        List<GroupMessageWithUnreadVO> groupMessageWithUnreadVO = baseMapper.
                selectMessagesWithUnread(readSingleMessageDTO);

        // 收集所有未读消息的主键 id
        List<Integer> unreadIds = groupMessageWithUnreadVO.stream()
                .map(GroupMessageWithUnreadVO::getGroupMessageUnreadId)
                .collect(Collectors.toList());

        update(new LambdaUpdateWrapper<GroupMessageUnread>()
                .in(GroupMessageUnread::getId, unreadIds)
                .set(GroupMessageUnread::getReadStatus, ReadStatus.READ)
                .set(GroupMessageUnread::getReadTime, LocalDateTime.now()));

        return Result.success("消息状态修改成功", groupMessageWithUnreadVO);
    }

    @Override
    public Result readAllGroupChatMessage(ReadAllMessageDTO readAllMessageDTO) {
        int update = baseMapper.readAllGroupChatMessage(readAllMessageDTO);

        return Result.success("消息状态修改成功", "修改了" + update + "消息状态");
    }

    @Override
    public Result readAllMessage(Integer userId) {
        int groupUpdated = baseMapper.updateAllGroupMessages(userId);
        int friendUpdated = userMessageMapper.updateAllFriendMessages(userId);
        int total = groupUpdated + friendUpdated;

        return Result.success("消息状态修改成功", "修改了" + total + "消息状态");
    }
}
